<template>
  <div class="login-container">
    <div class="login-box">
      <h2>校园失物登记与招领平台</h2>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名/手机号"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="handleLogin" :loading="loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div class="login-links">
        <el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
        <el-link type="primary" @click="showResetDialog = true">忘记密码</el-link>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog v-model="showResetDialog" title="重置密码" width="500px" :close-on-click-modal="false">
      <el-steps :active="resetStep" finish-status="success" align-center>
        <el-step title="验证手机号" />
        <el-step title="验证验证码" />
        <el-step title="设置新密码" />
        <el-step title="完成" />
      </el-steps>

      <!-- 步骤1：输入手机号并发送验证码 -->
      <el-form v-if="resetStep === 0" :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" style="margin-top: 30px">
        <el-alert
          title="请输入注册时使用的手机号"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        />
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            style="width: 100%" 
            @click="handleSendCode" 
            :loading="sendCodeLoading"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 步骤2：输入验证码 -->
      <el-form v-if="resetStep === 1" :model="codeForm" :rules="codeRules" ref="codeFormRef" style="margin-top: 30px">
        <el-alert
          :title="`验证码已发送至 ${maskedPhone}`"
          type="success"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template v-if="devCode">
            <div style="margin-top: 10px; color: #E6A23C;">
              <strong>【测试用】验证码：{{ devCode }}</strong>
            </div>
          </template>
        </el-alert>
        <el-form-item label="验证码" prop="code">
          <el-input 
            v-model="codeForm.code" 
            placeholder="请输入6位验证码" 
            maxlength="6"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="text" 
            @click="handleResendCode"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `${countdown}秒后` : '' }}重新发送验证码
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 步骤3：设置新密码 -->
      <el-form v-if="resetStep === 2" :model="resetForm" :rules="resetRules" ref="resetFormRef" style="margin-top: 30px">
        <el-alert
          title="验证码验证成功！"
          type="success"
          :closable="false"
          style="margin-bottom: 20px"
        />
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetForm.newPassword" type="password" placeholder="请输入新密码（6-20位）" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
      </el-form>

      <!-- 步骤4：完成 -->
      <div v-if="resetStep === 3" style="text-align: center; padding: 40px 0;">
        <el-result icon="success" title="密码重置成功！" sub-title="请使用新密码登录">
          <template #extra>
            <el-button type="primary" @click="closeResetDialog">返回登录</el-button>
          </template>
        </el-result>
      </div>

      <template #footer v-if="resetStep < 3">
        <span>
          <el-button @click="closeResetDialog">取消</el-button>
          <el-button v-if="resetStep === 1" @click="resetStep = 0">
            上一步
          </el-button>
          <el-button v-if="resetStep === 1" type="primary" @click="handleVerifyCode" :loading="verifyLoading">
            下一步
          </el-button>
          <el-button v-if="resetStep === 2" @click="resetStep = 1">
            上一步
          </el-button>
          <el-button v-if="resetStep === 2" type="primary" @click="handleResetPassword" :loading="resetLoading">
            确认重置
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, sendVerifyCode, verifyCode, resetPassword } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const phoneFormRef = ref(null)
const codeFormRef = ref(null)
const resetFormRef = ref(null)
const loading = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名/手机号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 忘记密码对话框
const showResetDialog = ref(false)
const resetStep = ref(0)
const sendCodeLoading = ref(false)
const verifyLoading = ref(false)
const resetLoading = ref(false)
const countdown = ref(0)
const maskedPhone = ref('')
const devCode = ref('') // 开发环境下显示验证码

// 手机号表单
const phoneForm = reactive({
  phone: ''
})

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}

// 验证码表单
const codeForm = reactive({
  code: ''
})

const codeRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 重置密码表单
const resetForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const resetRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 登录
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await login(loginForm)
        userStore.setToken(res.data.token)
        userStore.setUserInfo(res.data)
        ElMessage.success('登录成功')
        router.push('/')
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 发送验证码
const handleSendCode = () => {
  phoneFormRef.value.validate(async (valid) => {
    if (valid) {
      sendCodeLoading.value = true
      try {
        const res = await sendVerifyCode({ phone: phoneForm.phone })
        maskedPhone.value = res.data.phone
        devCode.value = res.data.code // 开发环境显示验证码
        ElMessage.success(res.msg)
        resetStep.value = 1
        startCountdown()
      } catch (error) {
        console.error(error)
      } finally {
        sendCodeLoading.value = false
      }
    }
  })
}

// 重新发送验证码
const handleResendCode = () => {
  sendCodeLoading.value = true
  sendVerifyCode({ phone: phoneForm.phone })
    .then(res => {
      devCode.value = res.data.code
      ElMessage.success('验证码已重新发送')
      startCountdown()
    })
    .catch(error => {
      console.error(error)
    })
    .finally(() => {
      sendCodeLoading.value = false
    })
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 验证验证码
const handleVerifyCode = () => {
  codeFormRef.value.validate(async (valid) => {
    if (valid) {
      verifyLoading.value = true
      try {
        await verifyCode({
          phone: phoneForm.phone,
          code: codeForm.code
        })
        ElMessage.success('验证码验证成功')
        resetStep.value = 2
      } catch (error) {
        console.error(error)
      } finally {
        verifyLoading.value = false
      }
    }
  })
}

// 重置密码
const handleResetPassword = () => {
  resetFormRef.value.validate(async (valid) => {
    if (valid) {
      resetLoading.value = true
      try {
        await resetPassword({
          phone: phoneForm.phone,
          code: codeForm.code,
          newPassword: resetForm.newPassword
        })
        ElMessage.success('密码重置成功')
        resetStep.value = 3
      } catch (error) {
        console.error(error)
      } finally {
        resetLoading.value = false
      }
    }
  })
}

// 关闭重置密码对话框
const closeResetDialog = () => {
  showResetDialog.value = false
  resetStep.value = 0
  countdown.value = 0
  maskedPhone.value = ''
  devCode.value = ''
  // 重置表单
  Object.assign(phoneForm, { phone: '' })
  Object.assign(codeForm, { code: '' })
  Object.assign(resetForm, { newPassword: '', confirmPassword: '' })
  // 重置表单验证
  phoneFormRef.value?.resetFields()
  codeFormRef.value?.resetFields()
  resetFormRef.value?.resetFields()
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.login-links {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-top: 15px;
  padding: 0 5px;
}

.login-links :deep(.el-link) {
  font-size: 14px;
  transition: all 0.3s ease;
}

.login-links :deep(.el-link:hover) {
  font-weight: 500;
  transform: translateY(-1px);
}
</style>

